import { defineStore } from 'pinia'
import DuUtil from '../utils/DuUtil'
import cacheStoreCreater from './cacheStore'
import { dashboardRoute } from '@/router/modules/index.js'

/*
 { 
   path: 路由地址,
   title: 标题,
   closable: 是否可以关闭,
   popoverVisible: 控制popover菜单显示,
   cache: 是否缓存 
 }
 */

const tabsStore = defineStore({
  id: 'tabsState',
  state: () => ({
    tabs: [],
    activePath: null, // 当前route的地址
  }),
  getters: {
    getTheLastTab() {
      return this.tabs[this.tabs.length - 1]
    },
    getIndexTab() {
      return this.tabs.find((tab) => !tab.closable)
    },
  },
  actions: {
    // 关闭当前
    removeTab(tab) {
      if (!tab.closable) {
        return ''
      }
      if (this.tabs.length === 1) {
        return ''
      }
      DuUtil.arrayRemove(this.tabs, tab)
      this.resetCacheName()
      if (this.activePath === tab.path) {
        return this.getTheLastTab.path
      } else {
        return ''
      }
    },
    // 关闭其他
    removeOtherTab(tab) {
      tab.popoverVisible = false
      this.tabs = this.tabs.filter((t) => !t.closable || t.path === tab.path)
      this.resetCacheName()
      if (this.activePath === tab.path) {
        return ''
      } else {
        return tab.path
      }
    },
    // 关闭全部
    clearTabs() {
      this.$patch((state) => {
        state.tabs = this.tabs.filter((t) => !t.closable)
      })
      this.resetCacheName()
      return this.tabs[0].path
    },
    // 添加tab标签，并设置当前tab
    addTab(router) {
      const ifHave = this.tabs.some((item) => item.path === router.path)
      // 如果tab标签里有该路由
      if (ifHave) {
        this.setActive(router.path)
        return
      }

      if (router.path === dashboardRoute.path) {
        this.addTabByRouter(dashboardRoute, false)
      } else {
        if (this.tabs.length === 0) {
          this.addTabByRouter(dashboardRoute, false)
        }
        this.addTabByRouter(router, true)
      }

      this.activePath = router.path
    },
    // 添加首页tab
    addTabByRouter(router, ifClosable) {
      const path = router.path
      const title = router.meta.title
      const cache = router.meta.cache
      this.tabs.push({
        path,
        title,
        closable: ifClosable,
        popoverVisible: false,
        cache,
      })
    },
    // 设置选中的tab
    setActive(path) {
      this.activePath = path
    },
    // 取消所有popover
    setAllPopoverHide() {
      this.$patch((state) => {
        state.tabs.forEach((tab) => {
          tab.popoverVisible = false
        })
      })
    },
    // 重置缓存
    resetCacheName() {
      const cacheStore = cacheStoreCreater()
      cacheStore.resetCacheName()
    },
  },
})
export default tabsStore
